var haveRoleId='';

$(function(){
	getMyRoles();
	getSelectUserRoles();
});


function roleAdd() {
	var roleIds="";
	$('input[name="roleId"]:checked').each(function() {
		roleIds+=$(this).attr("id")+",";
	});
	
	var r1=haveRoleId.split(',');//原有
	var r2=roleIds.split(',');//现有
	var str='';//变少了的角色
	
	for (var i=0;i<r1.length;i++){ 
		 var flag=false;
		 for (var j=0;j<r2.length;j++){   
	         if(r1[i]==r2[j]){
	        	 flag=true;
	        	 break;
	         }
		 } 
		 if(!flag){
			 str+=r1[i]+',';
		 }
	}

	jconfirm("doSet('"+roleIds+"','"+userId+"','"+str+"')",
			"此操作将会影响该用户授予其他角色的权限，是否要继续授权？");	
	
}


function doSet(roleIds,userId,str){
	$.ajax({
		url : ctp + "/sysuserController/roleAdd.shtml",
		data : {roleIds:roleIds,userId:userId,roleLst:str},
		type : 'POST',
		async : false,
		success : function(result) {
			if (result == "") {
				jalert9("授权成功！");
				setTimeout(function(){
					parent.searchData();
					back();
				},WARN_TIME_OUT);
			} else {
				jalert(result);
			}
		}
	});
}


function getSelectUserRoles(){
	$.ajax({
		url : ctp + "/sysuserController/getSelectUserRoles.shtml",
		data : {
			userId:userId
		},
		type : 'POST',
		async : false,
		dataType : 'json',
		success : function(result) {
				var roleList=result.userRoles;
				 if(roleList.length>0){ 
					 $.each(roleList,function(i){
						 if(roleList[i]!=null){
						 $("#"+roleList[i].REC_ID).attr("checked","checked");
						 haveRoleId+=roleList[i].REC_ID+',';
						 }
					 });
				 }
		}
	});
}


function getMyRoles(){
	$.ajax({
		url : ctp + "/sysuserController/getSelectUserRoles.shtml",
		data : {
			userId:loginUserId
		},
		type : 'POST',
		async : false,
		dataType : 'json',
		success : function(result) {
				var roleList=result.userRoles;
				$("#roleBody").html("");
				 if(roleList.length>0){ 
					 $.each(roleList,function(i){
						 if(roleList[i]!=null){
							 $("#"+roleList[i].REC_ID).attr("checked","checked");
							 var html='<div class="add-role-item"><input type="radio" id="'+roleList[i].REC_ID+'" name="roleId" /> <span>'+roleList[i].ROLE_NAME+'</span>';
							     html +='<div class="role-show-detail">';
							     var l1 = getRolePower(roleList[i].REC_ID);
							     var l = l1.list;
							     for (var j = 0; j < l.length; j++) {
							    	 html +='<p>'+l[j].MODULE_NAME+'</p>';
								}
						    	 html +='</div></div>';
							    	 
							 $("#roleBody").append(html); 
						 }
					 });
				 }
		}
	});
}

function getRolePower(roleId){
	var data = "";
	$.ajax({
		url : ctp + "/sysuserController/getRolePower.shtml",
		data : {
			roleId:roleId
		},
		type : 'POST',
		async : false,
		dataType : 'json',
		success : function(result) {
			data = result;
		}
	});
	return data;
}

function back() {
	window.parent.closeDialogWin();
}